/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.goods.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.config.Global;
import com.jeesite.common.service.ServiceException;
import com.jeesite.common.utils.excel.ExcelExport;
import com.jeesite.common.utils.excel.ExcelImport;
import com.jeesite.common.utils.excel.annotation.ExcelField;
import com.jeesite.modules.pay.totalPay.util.StringUtil;
import com.jeesite.modules.xcxAdmin.service.ZtAdminService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeesite.common.entity.Page;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.goods.entity.ZtFinancial;
import com.jeesite.modules.goods.service.ZtFinancialService;
import com.jeesite.modules.xcxAdmin.entity.ZtAdmin;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * 测试数据Controller
 * 
 * @author ThinkGem
 * @version 2018-04-22
 */
@Controller
@RequestMapping(value = "${adminPath}/ztFinancial")
public class ZtFinancialController extends BaseController {

	@Autowired
	private ZtFinancialService ztFinancialService;

	@Autowired
	private ZtAdminService ztAdminService;
	/**
	 * 获取数据
	 */
	@ModelAttribute
	public ZtFinancial get(String id, boolean isNewRecord) {
		ZtFinancial ztFinancial=new ZtFinancial();
		ztFinancial.setId(id);
		return ztFinancialService.get(ztFinancial);
	}

	/**
	 * 查询列表
	 */
	@RequestMapping(value = { "list", "" })
	public String list(ZtFinancial ztFinancial, Model model,HttpSession session) {
		if(ztFinancial!=null && ztFinancial.getZtAdmin()!=null && StringUtils.isNotBlank(ztFinancial.getZtAdmin().getId())){
			session.setAttribute("ztFinancialAdminid", ztFinancial.getZtAdmin().getId());
		}else{
			if(ztFinancial==null){ztFinancial=new ZtFinancial();}
			ZtAdmin ztAdmin=new ZtAdmin();
			ztAdmin.setId(session.getAttribute("ztFinancialAdminid").toString());
			ztFinancial.setZtAdmin(ztAdmin);
		}
		
		model.addAttribute("ztFinancial", ztFinancial);
		
		
		return "modules/ztFinancial/ztFinancialList";
	}

	/**
	 * 查询列表数据
	 */
	
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<ZtFinancial> listData(ZtFinancial ztFinancial, HttpServletRequest request,
			HttpServletResponse response,Model model,HttpSession session) {
		
		session.getAttribute("ztAdminId");
		
		Page<ZtFinancial> page = ztFinancialService.findPage(new Page<ZtFinancial>(request,
				response), ztFinancial);
		
		
		return page;
	}
	@RequiresPermissions("admin:adminData:view")
	@RequestMapping(value = "listAudit")
	public String list(ZtFinancial ztFinancial, Model model) {
		model.addAttribute("ZtFinancial", ztFinancial);
		return "modules/ztFinancial/ztFinancialAudit";
	}

	@ResponseBody
	@RequiresPermissions("admin:adminData:view")
	@RequestMapping(value = "listselfData")
	public Page<ZtFinancial> getRecahrgeRecord(ZtFinancial ztFinancial, HttpServletRequest request,
													HttpServletResponse response){

		Page<ZtFinancial> page = ztFinancialService.findPage(new Page<ZtFinancial>(request,
				response), ztFinancial);
		return page;
	}
	/**
	 * 导入用户数据
	 */
	@ResponseBody
	@RequiresPermissions("sys:empUser:edit")
	@PostMapping(value = "importData")
	public Map<String,Object> importData(MultipartFile file) {
		Map<String,Object> map = new HashMap<>();
		try {
			map= importDataMap(file);
			map.put("ret",200);
			return map;
		} catch (Exception ex) {
			map.put("ret",300);
			map.put("message","导入充值失败！");
			return map;
		}
	}

	/**
	 * 下载导出用户数据模板
	 */
	@RequiresPermissions("sys:empUser:view")
	@RequestMapping(value = "exportData")
	public void exportData(ZtFinancial ztFinancial, HttpServletRequest request,
							   HttpServletResponse response) {
        Page<ZtFinancial> ztFinancialPage = new Page<>(request, response);
        ztFinancialPage.setPageNo(1);
        ztFinancialPage.setPageSize(10000);
        Page<ZtFinancial> page = ztFinancialService.findPage(ztFinancialPage, ztFinancial);
		List<ZtFinancial> list = page.getList();
		String fileName = "用户充值数据审核.xlsx";
		new ExcelExport("用户充值数据", ZtFinancial.class, ExcelField.Type.IMPORT).setDataList(list)
				.write(response, fileName).dispose();
	}

	/**
	 * 下载导入用户数据模板
	 */
	@RequiresPermissions("sys:empUser:view")
	@RequestMapping(value = "importTemplate")
	public void importTemplate(HttpServletResponse response) {
		ZtFinancial ztFinancial = new ZtFinancial();
		List<ZtFinancial> list = ListUtils.newArrayList(ztFinancial);
		String fileName = "用户充值数据模板.xlsx";
		new ExcelExport("用户充值数据", ZtFinancial.class, ExcelField.Type.IMPORT).setDataList(list)
				.write(response, fileName).dispose();
	}
	/**
	 * 导入用户数据
	 * @param file 导入的用户数据文件
	 */
	public Map<String,Object> importDataMap(MultipartFile file) {
		if (file == null){
			throw new ServiceException("请选择导入的数据文件！");
		}
		int successNum = 0; int failureNum = 0;
		double cashAmountSum = 0D;
		Map<String,Object> map = new HashMap<>();
		try {
			ExcelImport ei = new ExcelImport(file, 2, 0);

			List<ZtFinancial> list = ei.getDataList(ZtFinancial.class);
			for (ZtFinancial record : list) {
				try{
					if (record!=null){
						successNum++;
						cashAmountSum += record.getPrice();
					}else {
						failureNum++;
					}
				} catch (Exception e) {
					failureNum++;
					logger.error( "导入异常",e);
				}
			}
			map.put("number",successNum);
			map.put("cashAmountSum",cashAmountSum);
			map.put("list",list);
		} catch (Exception e) {
			logger.error("导入异常", e);
		}
		return map;//successMsg.toString();
	}

	@ResponseBody
	@RequiresPermissions("admin:adminData:view")
	@RequestMapping(value = "topUp")
	public String topUp(String str){
		JSONObject jo = JSONObject.parseObject(str);
		try{
			JSONArray ja = jo.getJSONArray("userCodes");
			double cashAmount=jo.getDouble("cashAmount");
			List<ZtAdmin> admins = new ArrayList<>();
			List<ZtFinancial> ztFinancials = new ArrayList<>();
			for (int i=0;i<ja.size();i++){
				ZtAdmin ztAdmin = new ZtAdmin();
				ztAdmin.setId(ja.getString(i));
				ztAdmin=ztAdminService.get(ztAdmin);
				if(ztAdmin!=null){
					ztAdmin.setCashAmount(cashAmount);
					admins.add(ztAdmin);
					ZtFinancial ztFinancial = new ZtFinancial();
					ztFinancial.setZtAdmin(ztAdmin);
					ztFinancial.setPricestr("+￥"+cashAmount);
					ztFinancial.setStatus("0");
					ztFinancial.setType("2");
					ztFinancial.setAudit("2");//已经审核
					ztFinancial.setContent("客服充值");
					ztFinancial.setCompanyId(ztAdmin.getCompany());
					ztFinancial.setHeadimgurl(ztAdmin.getHeadimgurl());
					ztFinancial.setUsername(ztAdmin.getUsername());
					ztFinancial.setPhone(ztAdmin.getPhone());
					ztFinancial.setCreateDate(new Date());
					ztFinancial.setPrice(cashAmount);
					ztFinancial.setOperation("系统管理员");
					ztFinancials.add(ztFinancial);
				}

			}
			if(ztFinancials.size()>0){
				ztFinancialService.insertBatch(ztFinancials);
			}
			if(admins.size()>0){
				ztAdminService.updateCashAmountList(admins);
			}
			return  renderResult(Global.TRUE, "posfull:充值成功！");
		}catch (Exception e){
			logger.error("充值异常",e);
			return  renderResult(Global.TRUE, "posfull:充值异常");
		}

	}
	@ResponseBody
	@RequiresPermissions("admin:adminData:view")
	@RequestMapping("audit")
	public String audit(String str){
		try{
			if(StringUtil.isNotEmpty(str)){
				 String [] arr	= str.split(",");
				 List<ZtFinancial> list = new ArrayList<>();
				 List<ZtAdmin> ztAdmins = new ArrayList<>();

				 for (String id:arr){
				 	ZtFinancial ztFinancial = new ZtFinancial();
					ztFinancial.setId(id);
					ztFinancial=ztFinancialService.get(ztFinancial);
					if(ztFinancial!=null){
						ztFinancial.setType("2");
						ztFinancial.setAudit("2");
						ZtAdmin ztAdmin = new ZtAdmin();
						ztAdmin.setId(ztFinancial.getZtAdmin().getId());
						ztAdmin.setCashAmount(ztFinancial.getPrice());
						ztAdmins.add(ztAdmin);
						list.add(ztFinancial);
					}
				 }
				if(ztAdmins.size()>0){
					ztAdminService.updateCashAmountList(ztAdmins);
				}
				if(list.size()>0){
					ztFinancialService.updatePriceList(list);
				}
			}

				return renderResult(Global.TRUE, "审核充值成功！");
			}catch (Exception e){
			logger.error("充值异常",e);
			return  renderResult(Global.TRUE, "posfull:审核充值异常");
		}

	}

	@ResponseBody
	@RequiresPermissions("admin:adminData:view")
	@RequestMapping("topUpTemplate")
	public String topUpTemplate(String list,HttpServletResponse response){
		if(StringUtil.isNotEmpty(list)){
			try {
				JSONArray  ztFinancials = JSONObject.parseArray(list);
				ZtAdmin ztAdmin = new ZtAdmin();
				List<ZtFinancial> ztFinancials1 = new ArrayList<>();
                List<ZtAdmin> ztFinancials2 = new ArrayList<>();
				StringBuilder successMsg = new StringBuilder();
				for (int i =0 ; i<ztFinancials.size();i++){
					ZtFinancial ztFinancial = ztFinancials.getJSONObject(i).toJavaObject(ZtFinancial.class);
					ztAdmin.setPhone(ztFinancial.getPhone());
					ztAdmin = ztAdminService.getByPhone(ztAdmin);
					if(ztAdmin!=null){
						if(ztAdmin.getCompany().equals(ztFinancial.getCompanyId())){
							ztFinancial.setZtAdmin(ztAdmin);
							ztFinancial.setPricestr("+￥"+ztFinancial.getPrice());
							ztFinancial.setType("1");
							ztFinancial.setAudit("1");
							ztFinancial.setStatus("0");
							ztFinancial.setHeadimgurl(ztAdmin.getHeadimgurl());
							ztFinancial.setCreateDate(new Date());
							ztFinancials1.add(ztFinancial);
							successMsg.append("<br/>" + (i+1) + "、账号 " + ztFinancial.getUsername() + " 充值成功，待审核中！");
						}else {
                            ztFinancials2.add(ztAdmin);
							successMsg.append("<br/>" + (i+1) + "、账号: " + ztFinancial.getUsername() + "   用户绑定的与导入的公司不匹配，无法充值");
						}
					}else {
                        ztFinancials2.add(ztAdmin);
						successMsg.append("<br/>" + (i+1) + "、该手机号码: " + ztFinancial.getPhone()  + "   没有匹配到用户，无法充值");
					}
				}
				if(ztFinancials2.size()>0){
					String fileName = "用户充值数据模板.xlsx";
					new ExcelExport("用户充值数据", ZtFinancial.class, ExcelField.Type.IMPORT).setDataList(ztFinancials2)
							.write(response, fileName).dispose();
				}
				if(ztFinancials1.size()>0){
					ztFinancialService.insertBatch(ztFinancials1);
				}

				successMsg.insert(0, "充值信息" + ztFinancials.size() + " 条，数据如下：");
				return renderResult(Global.TRUE, "posfull:"+successMsg.toString());
			}catch (Exception e){
				logger.error("充值异常",e);
				return renderResult(Global.FALSE, "posfull:充值环境异常");
			}
		}else {
			return renderResult(Global.FALSE, "posfull:充值信息环境有误");
		}

	}
}